from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
import json
from bs4 import BeautifulSoup
import re
import urllib.request

def chat(request):

    api_url = "http://openapi.tuling123.com/openapi/api/v2"
    text_input = request.POST.get('question','abc')
    userId = request.POST.get('userId', 'abc')
    # text_input = "你要上天"

    req = {
        "perception":
        {
            "inputText":
            {
                "text": text_input
            },

            "selfInfo":
            {
                "location":
                {
                    "city": "深圳",
                    "province": "深圳",
                    "street": ""
                }
            }
        },

        "userInfo":
        {
            "apiKey": "ff539ae005034a5aad2e8c82344e7992",
            "userId": userId
        }
    }
    # print(req)
    # 将字典格式的req编码为utf8
    req = json.dumps(req).encode('utf8')
    # print(req)

    http_post = urllib.request.Request(api_url, data=req, headers={'content-type': 'application/json'})
    response = urllib.request.urlopen(http_post)
    response_str = response.read().decode('utf8')
    # print(response_str)
    response_dic = json.loads(response_str)
    # print(response_dic)

    intent_code = response_dic['intent']['code']
    results_text = response_dic['results'][0]['values']['text']
    return HttpResponse(json.dumps(
        {
            "answer":results_text,
            "type":1
        }
    ), content_type="application/json")
    # print('Turing的回答：')
    # print('code：' + str(intent_code))
    # print('text：' + results_text)

